package club.gggd.mimotion.schedule;

import club.gggd.mimotion.util.SecretUtil;
import club.gggd.mimotion.vo.MiResult;
import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Description
 * @Author srx
 * @date 2022/4/2 17:19
 */
@Component
@Slf4j
public class MiSchedule {

    public static Map<String, String> info = new HashMap<>();

    private static ObjectMapper objectMapper = new ObjectMapper();

    private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    @Value("${email.url}")
    private String URL;

    @Value("${email.user}")
    private String EMAIL_USER;

    @Value("${email.pass}")
    private String EMAIL_PASS;

    private final String PORT = "587";

    static {
        // 转换为格式化的json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        // 如果json中有新增的字段并且是实体类类中不存在的，不报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Scheduled(cron = "${time.cron}")
    public void exec(){
        info.forEach((key, value) -> {
            String[] values = value.split(",");
            String phoneNumber = key;
            String password = SecretUtil.desEncrypt(values[0]);
            String email = values[1];
            log.info("正在自动刷步，账号：{},邮箱：{}", phoneNumber, email);
            int steps = Integer.parseInt(values[2]);
            //开始
            int step = getRandom(steps + 500, steps);
            String accessCode = getAccessCode(phoneNumber, password);
            Map<String, String> login = login(accessCode);
            String login_token = login.get("login_token");
            String user_id = login.get("user_id");
            String appToken = getAppToken(login_token);
            String r = updateStep(appToken, user_id,step);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                MiResult miResult = objectMapper.readValue(r, MiResult.class);
                sendEmail(miResult, step, email);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        });
    }

    public void sendEmail(MiResult miResult, int step, String email){
        log.info("开始发送信息至邮箱：{}", email);
        String title = "";
        String context = "";
        if(miResult.getCode() == 1){
            title = "刷步成功";
            context = "刷步成功，本次刷步：" + step + "步。<br>本邮件为系统自动发送，请勿回复。";
        } else {
            title = "刷步失败";
            context = "刷步失败，请前往" + URL + " 手动操作。";
        }
        //开始发送邮件

        // 创建Properties 类用于记录邮箱的一些属性
        Properties props = new Properties();
        // 表示SMTP发送邮件，必须进行身份验证
        props.put("mail.smtp.auth", "true");
        //此处填写SMTP服务器
        props.put("mail.smtp.host", "smtp.qq.com");
        //端口号，QQ邮箱给出了两个端口，但是另一个我一直使用不了，所以就给出这一个587
        props.put("mail.smtp.port", PORT);
        // 此处填写你的账号
        props.put("mail.user", EMAIL_USER);
        // 此处的密码就是前面说的16位STMP口令
        props.put("mail.password", EMAIL_PASS);

        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName,password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form;
        try {
            form = new InternetAddress(props.getProperty("mail.user"));
            message.setFrom(form);
            // 设置收件人的邮箱
            message.setRecipients(Message.RecipientType.TO, email);
            // 设置邮件标题
            message.setSubject(title);
            // 设置邮件的内容体
            message.setContent(context, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
        } catch(Exception e) {
            e.printStackTrace();
            log.error("发送给：{}的邮件出错", email);
        }
    }

    public String getAccessCode(String account,String password) {
        try {
            URIBuilder builder = new URIBuilder("https://api-user.huami.com/registrations/+86" + account + "/tokens");
            HashMap<String, String> data = new HashMap<>();
            data.put("client_id", "HuaMi");
            data.put("password",password);
            data.put("redirect_uri", "https://s3-us-west-2.amazonaws.com/hm-registration/successsignin.html");
            data.put("token", "access");
            data.forEach(builder::setParameter);
            HttpPost httpPost = new HttpPost(builder.build());
            httpPost.setConfig(RequestConfig.custom()
                    .setSocketTimeout(5000)
                    ////默认允许自动重定向
                    .setRedirectsEnabled(false)
                    .build());
            httpPost.addHeader("User-Agent", "MiFit/4.6.0 (iPhone; iOS 14.0.1; Scale/2.00)");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            HttpResponse execute = httpClient.execute(httpPost);
            int statusCode = execute.getStatusLine().getStatusCode();
            Header location = execute.getFirstHeader("Location");
            String params = location.getValue().substring(location.getValue().indexOf("?") + 1);
            Map<String, String> split = Splitter.on("&").withKeyValueSeparator("=").split(params);
            String s = split.get("access");
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Map<String, String> login(String accessCode) {
        try {
            HashMap<String, String> data1 = new HashMap<>();
            data1.put("app_version", "4.6.0");
            data1.put("code",accessCode);
            data1.put("country_code", "CN");
            data1.put("device_id", "2C8B4939-0CCD-4E94-8CBA-CB8EA6E613A1");
            data1.put("device_model", "phone");
            data1.put("grant_type", "access_token");
            data1.put("third_name", "huami_phone");
            data1.put("app_name", "com.xiaomi.hm.health");
            URIBuilder builder1 = new URIBuilder("https://account.huami.com/v2/client/login");
            data1.forEach(builder1::setParameter);
            HttpPost httpPost1 = new HttpPost(builder1.build());
            httpPost1.addHeader("User-Agent", "MiFit/4.6.0 (iPhone; iOS 14.0.1; Scale/2.00)");
            httpPost1.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            HttpResponse execute1 = httpClient.execute(httpPost1);
            String s1 = EntityUtils.toString(execute1.getEntity());
            JsonNode jsonNode = objectMapper.readTree(s1);
            String login_token = jsonNode.get("token_info").get("login_token").asText();
            String user_id = jsonNode.get("token_info").get("user_id").asText();
            HashMap<String, String> map = new HashMap<>();
            map.put("login_token", login_token);
            map.put("user_id", user_id);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getAppToken(String login_token) {
        try {
            HttpGet httpGet = new HttpGet("https://account-cn.huami.com/v1/client/app_tokens?app_name=com.xiaomi.hm.health&dn=api-user.huami.com%2Capi-mifit.huami.com%2Capp-analytics.huami.com&login_token=" + login_token + "&os_version=4.1.0");
            CloseableHttpResponse execute3 = httpClient.execute(httpGet);
            String s3 = EntityUtils.toString(execute3.getEntity());
            String app_token = objectMapper.readTree(s3).get("token_info").get("app_token").asText();
            return app_token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String updateStep(String appToken, String userId, Integer step) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH");
        LocalDateTime localDateTime = LocalDateTime.now();
        String hour = dateTimeFormatter.format(localDateTime);
        if(step == null || step <= 0){
            step = 0;
        }
        if(step >= 98800){
            //超出则最大为98800
            step = 98800;
        }

        String jsonData = "[{\"summary\":\"{\\\"slp\\\":{\\\"ss\\\":73,\\\"lt\\\":304,\\\"dt\\\":0,\\\"st\\\":1589920140,\\\"lb\\\":36,\\\"dp\\\":92,\\\"is\\\":208,\\\"rhr\\\":0,\\\"stage\\\":[{\\\"start\\\":269,\\\"stop\\\":357,\\\"mode\\\":2},{\\\"start\\\":358,\\\"stop\\\":380,\\\"mode\\\":3},{\\\"start\\\":381,\\\"stop\\\":407,\\\"mode\\\":2},{\\\"start\\\":408,\\\"stop\\\":423,\\\"mode\\\":3},{\\\"start\\\":424,\\\"stop\\\":488,\\\"mode\\\":2},{\\\"start\\\":489,\\\"stop\\\":502,\\\"mode\\\":3},{\\\"start\\\":503,\\\"stop\\\":512,\\\"mode\\\":2},{\\\"start\\\":513,\\\"stop\\\":522,\\\"mode\\\":3},{\\\"start\\\":523,\\\"stop\\\":568,\\\"mode\\\":2},{\\\"start\\\":569,\\\"stop\\\":581,\\\"mode\\\":3},{\\\"start\\\":582,\\\"stop\\\":638,\\\"mode\\\":2},{\\\"start\\\":639,\\\"stop\\\":654,\\\"mode\\\":3},{\\\"start\\\":655,\\\"stop\\\":665,\\\"mode\\\":2}],\\\"ed\\\":1589943900,\\\"wk\\\":0,\\\"wc\\\":0},\\\"tz\\\":\\\"28800\\\",\\\"stp\\\":{\\\"runCal\\\":1,\\\"cal\\\":6,\\\"conAct\\\":0,\\\"stage\\\":[],\\\"ttl\\\":" + step + ",\\\"dis\\\":144,\\\"rn\\\":0,\\\"wk\\\":5,\\\"runDist\\\":4,\\\"ncal\\\":0},\\\"v\\\":5,\\\"goal\\\":8000}\",\"data\":[{\"stop\":1439,\"value\":\"WhQAUA0AUAAAUAAAUAAAUAAAUAAAWhQAUAYAcBEAUAYAUA8AUAsAUAYAUDIAUCQAUDkAUCkAUD4AUC0AUFcAUD8AUCkAUCEAUCwAUCsAUB4AUCQAUBsAUCcAUBQAUDcAUBoAUCYAUFcAUCAAUDkAUCEAWhQAWhQAWhQAUBAAUEgAUDsAUAgAWhQAUDwAUCEAUAIAUAsAUDoAUD8AWhQAWhQAWhQAWhQAWhQAWhQAAS0QEAsAWhQAAR8SEBcHYC4AUCoAUBMAUAIAUAYAUAsAUCsAUAUAUBIAUBIAUBsAUBgAUAoAUBsAUBUAUBkAUDIAUC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7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\\/v7+\",\"summary_hr\":\"{\\\"ct\\\":0,\\\"id\\\":[]}\",\"date\":\"" + format + "\"}]";
        HashMap<String, Object> dataUpdate = new HashMap<>();
        dataUpdate.put("data_json", jsonData);
        dataUpdate.put("userid", userId);
        dataUpdate.put("device_type", "0");
        dataUpdate.put("last_sync_data_time", "1589917081");
        dataUpdate.put("last_deviceid", "DA932FFFFE8816E7");
        HashMap<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.12(0x17000c2d) NetType/WIFI Language/zh_CN");
        headers.put("apptoken", appToken);
        headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        HttpRequest post = HttpRequest.post("https://api-mifit-cn.huami.com/v1/data/band_data.json?&t=" + System.currentTimeMillis());
        post.addHeaders(headers);
        post.form(dataUpdate);
        String body = post.execute().body();
        return body;
    }

    public int getRandom(int max, int min){
        return  (int) (Math.random() * (max-min) + min);
    }
}
